package com.frank.config.es.config.utils;



import com.frank.config.es.config.annotation.FieldMapping;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Frank Zou
 * @version v0.0.1
 * @date 2024/12/25
 * @description
 */
public class ObjectToMapUtil {
    public static <T> Map<String, Object> convertToMap(T obj) {
        if (obj == null) {
            throw new IllegalArgumentException("Object cannot be null");
        }

        Map<String, Object> resultMap = new HashMap<>();
        Field[] fields = obj.getClass().getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);
            try {
                Object value = field.get(obj);
                if (value != null) {
                    // 获取注解值
                    if (field.isAnnotationPresent(FieldMapping.class)) {
                        FieldMapping mapping = field.getAnnotation(FieldMapping.class);
                        resultMap.put(mapping.value(), value);
                    }
                }
            } catch (IllegalAccessException e) {
                throw new RuntimeException("Failed to access field: " + field.getName(), e);
            }
        }

        return resultMap;
    }
}
